<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

define('IN_ADMIN_COMPONENT_CONTROLLER', 'true');

class DiscountCategoriesComponent
{
	function DiscountCategoriesComponent()
	{
	}

	function action(&$params, $action)
	{
		if ($action == 'Update') 
			return $this->edit($params);
		else
			return $this->query($params);
	}

	function query(&$params) 
	{
		$handle = get_class($this);

		$sqlQuery = 'select dc.discount_categories_id, dc.discount_categories_name from ' . TABLE_DISCOUNT_CATEGORIES . ' dc order by dc.discount_categories_name';
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		$i = 0;
		while($row = mysql_fetch_array($dataReturned))
		{
			$id = (int)$row['discount_categories_id'];
			$value{$handle}{$i}{'id'}= $id;
			$value{$handle}{$i}{'name'}= $row['discount_categories_name'];
			$i++;
		}

		$value{$handle . 'MetaData'}{'image_width_max'}= (int)SMALL_IMAGE_WIDTH;
		$value{$handle . 'MetaData'}{'image_height_max'}= (int)SMALL_IMAGE_HEIGHT;

		return $value;
	}

	function edit(&$params) 
	{
		$i = 0;
		while (true)
		{
			$i++;
			if ($i > 1000) break;

			$discountCategoryId = (int)$params['discountCategoryId-'.$i];
			if ($discountCategoryId == 0) break;

			$discountCategoryName = prepare_input($params['discountCategoryName-'.$i]);
			if ($discountCategoryName == null || strlen($discountCategoryName) == 0) continue;

			$deleteRow = (boolean)$params['discountCategoryDelete-'.$i];

			if ($deleteRow) {
				if ($discountCategoryId < 1) continue;
				$sql = 'delete from ' . TABLE_DISCOUNT_CATEGORIES . ' where discount_categories_id=' . $discountCategoryId;
				mysql_query($sql) or die(mysql_error());
			}
			else {
				$sql_data_array = array();
				$sqlAction = 'insert';
				$where = '';
				if ($discountCategoryId > 0) {
					$sqlAction = 'update';
					$where = 'discount_categories_id=' . $discountCategoryId;
				}
				$sql_data_array['discount_categories_name'] = $discountCategoryName;
				db_perform(TABLE_DISCOUNT_CATEGORIES, $sql_data_array, $sqlAction, $where);
			}
		}

		return $this->query($params);
	}
}
?>
